package com.ihelin.insurance.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ihelin.insurance.entity.*;
import com.ihelin.insurance.service.*;
import com.ihelin.insurance.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author iHelin
 * @since 2021/2/27 15:00
 */
@RestController
public class AgentController {

    @Autowired
    private AgentService agentService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private PerformanceService performanceService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private FeedbackService feedbackService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private AnswerService answerService;

    /**
     * 代理人注册
     *
     * @param agentEntity
     * @return
     */
    @PostMapping("/agent/register")
    public R register(@RequestBody AgentEntity agentEntity) {
        String username = agentEntity.getUsername();
        List<AgentEntity> agentList = agentService.list(new QueryWrapper<AgentEntity>().eq("username", username));
        if (agentList != null && agentList.size() > 0) {
            return R.error("用户名已存在！");
        }
        agentEntity.setBasic(BigDecimal.ZERO);
        agentEntity.setPerformanceAmount(BigDecimal.ZERO);
        agentService.save(agentEntity);
        return R.ok();
    }

    /**
     * 代理人登录
     *
     * @param agentEntity
     * @param session
     * @return
     */
    @PostMapping("/agent/login")
    public R login(@RequestBody AgentEntity agentEntity, HttpSession session) {
        String username = agentEntity.getUsername();
        AgentEntity userFromDB = agentService.getOne(new QueryWrapper<AgentEntity>().eq("username", username));
        if (userFromDB != null && userFromDB.getPassword().equals(agentEntity.getPassword())) {
            session.setAttribute("agentUser", userFromDB);
            return R.ok();
        }
        return R.error("用户名或密码错误！");
    }

    /**
     * 客户列表
     */
    @GetMapping("/agent/customers/list")
    public R customers(Long page, Long limit, String key) {
        QueryWrapper<CustomerEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(key)) {
            queryWrapper.eq("id", key);
        }
        IPage<CustomerEntity> agentPage = customerService.page(new Page<>(page, limit), queryWrapper);
        return R.ok(agentPage);
    }

    /**
     * 客户信息
     */
    @GetMapping("/agent/customers/info/{id}")
    public R customerInfo(@PathVariable("id") Integer id) {
        CustomerEntity customer = customerService.getById(id);
        return R.ok().put("data", customer);
    }

    /**
     * 新增客户
     */
    @PostMapping("/agent/customers/save")
    public R saveCustomer(@RequestBody CustomerEntity customer, HttpSession session) {
        AgentEntity agentEntity = (AgentEntity) session.getAttribute("agentUser");
        customer.setAgentId(agentEntity.getId());
        customerService.save(customer);
        return R.ok();
    }

    /**
     * 修改客户
     */
    @PutMapping("/agent/customers/update")
    public R updateCustomer(@RequestBody CustomerEntity customer) {
        customerService.updateById(customer);
        return R.ok();
    }

    /**
     * 删除客户
     */
    @DeleteMapping("/agent/customers/delete")
    public R deleteCustomer(@RequestBody List<Integer> ids) {
        customerService.removeByIds(ids);
        return R.ok();
    }

    /**
     * agents列表
     */
    @GetMapping("/agent/agents/list")
    public R agentList(Long page, Long limit, String key) {
        QueryWrapper<AgentEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(key)) {
            queryWrapper.eq("id", key);
        }
        IPage<AgentEntity> agentPage = agentService.page(new Page<>(page, limit), queryWrapper);
        return R.ok(agentPage);
    }

    /**
     * 绩效列表
     */
    @GetMapping("/agent/performance/list")
    public R performances(Long page, Long limit, String key) {
        QueryWrapper<PerformanceEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(key)) {
            queryWrapper.eq("agent_id", key);
        }
        IPage<PerformanceEntity> data = performanceService.page(new Page<>(page, limit), queryWrapper);
        return R.ok(data);
    }

    @GetMapping("/agent/payment/list")
    public R payments(Long page, Long limit, String key) {
        QueryWrapper<PaymentEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(key)) {
            queryWrapper.eq("agent_id", key);
        }
        IPage<PaymentEntity> data = paymentService.page(new Page<>(page, limit), queryWrapper);
        return R.ok(data);
    }

    @GetMapping("/agent/feedback/list")
    public R feedbacks(Long page, Long limit, String key) {
        QueryWrapper<FeedbackEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(key)) {
            queryWrapper.eq("agent_id", key);
        }
        IPage<FeedbackEntity> data = feedbackService.page(new Page<>(page, limit), queryWrapper);
        return R.ok(data);
    }

    @PostMapping("/agent/feedback/save")
    public R saveFeedback(@RequestBody FeedbackEntity feedbackEntity, HttpSession session) {
        AgentEntity agentEntity = (AgentEntity) session.getAttribute("agentUser");
        feedbackEntity.setAgentId(agentEntity.getId());
        feedbackEntity.setAgentName(agentEntity.getName());
        feedbackService.save(feedbackEntity);
        return R.ok();
    }

    /**
     * Question列表
     */
    @GetMapping("/agent/question/list")
    public R questions(Long page, Long limit, String key, HttpSession session) {
        AgentEntity agentEntity = (AgentEntity) session.getAttribute("agentUser");
        QueryWrapper<QuestionEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(key)) {
            queryWrapper.eq("id", key);
        }
        IPage<QuestionEntity> data = questionService.page(new Page<>(page, limit), queryWrapper);
        List<QuestionEntity> questionEntities = data.getRecords();
        for (QuestionEntity questionEntity : questionEntities) {
            QueryWrapper<AnswerEntity> answerQueryWrapper = new QueryWrapper<>();
            answerQueryWrapper.eq("question_id", questionEntity.getId());
            answerQueryWrapper.eq("agent_id", agentEntity.getId());
            AnswerEntity answerEntity = answerService.getOne(answerQueryWrapper);
            if (answerEntity != null) {
                questionEntity.setAnswered(true);
                questionEntity.setAnswerContent(answerEntity.getContent());
                if (answerEntity.getScore() != null) {
                    questionEntity.setScored(true);
                    questionEntity.setScore(answerEntity.getScore());
                    questionEntity.setGrade(answerEntity.getGrade());
                } else {
                    questionEntity.setScored(false);
                    questionEntity.setScore(0);
                }
            } else {
                questionEntity.setAnswered(false);
                questionEntity.setScore(0);
            }
        }
        return R.ok(data);
    }

    /**
     * Question信息
     */
    @GetMapping("/agent/question/info/{id}")
    public R questionInfo(@PathVariable("id") Integer id) {
        QuestionEntity question = questionService.getById(id);
        return R.ok().put("data", question);
    }

    @PostMapping("/agent/question/answer")
    public R answerQuestion(@RequestBody AnswerEntity answerEntity, HttpSession session) {
        AgentEntity agentEntity = (AgentEntity) session.getAttribute("agentUser");
        answerEntity.setAgentId(agentEntity.getId());
        answerEntity.setAgentName(agentEntity.getName());
        answerService.save(answerEntity);
        return R.ok();
    }
}
